define(['jquery', 'bootstrap', 'backend', 'table', 'form','qrcode','jstree'], function ($, undefined, Backend, Table, Form,Qrcode,undefined) {
    
    //显示二维码
    showQrcode()
    
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'information/inventory/index' + location.search,
                    add_url: 'information/inventory/add',
                    edit_url: 'information/inventory/edit',
                    del_url: 'information/inventory/del',
                    multi_url: 'information/inventory/multi',
                    import_url: 'information/inventory/import',
                    table: 'inventory',
                }
            });

            var table = $("#table");
            
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'number',
                sortOrder: 'asc',
                singleSelect:false,
                fixedColumns: true,
                fixedRightNumber: 1,
                showToggle:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                       // {field: 'shelves_id', title: __('Shelves_id')},
                        //{field: 'image_url', title: '物料图片', searchList: {'0':'无图',"1":"有图"}, events: Table.api.events.image, formatter: Table.api.formatter.images,width:100},
                        {field: 'number', title: __('Number'), operate: 'LIKE'},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'specification', title: __('Specification'), operate: 'LIKE'},
                        //{field: 'attributes', title: __('Attributes'), operate: 'LIKE'},
                        {field: 'classification_name', title: __('Classification_name'), operate: 'LIKE'},
                       // {field: 'classification_id', title: __('Classification_id')},
                       // {field: 'switch', title: __('Switch'), searchList: {"0":__('Switch 0')," 1":__('Switch 1')},table: table, formatter: Table.api.formatter.toggle},
                        //{field: 'group', title: __('Group'), operate: 'LIKE'},
                        {field: 'unit', title: __('Unit'), operate: 'LIKE'},
                        {field: 'store_unit', title: __('StoreUnit'), operate: 'LIKE'},
                        //{field: 'ifshangjia', title: __('Ifshangjia'), searchList:{"0":__('Default'),"1":__('Shangkuqu'),"2":__('Shangjia')},formatter: Table.api.formatter.status },
                        //{field: 'ifjianhuo', title: __('Ifjianhuo'), searchList:{"0":__('Default'),"1":__('Jianhuo')},formatter: Table.api.formatter.status},
                        {field: 'warehouse.name', title: __('Warehouse_name'), operate: 'LIKE'},
                        {field: 'shelves.name', title: __('Shelves_name'), operate: 'LIKE'},
                        {field: 'invshlatest.warehouse_name', title: __('LWarehouse_name'), operate: 'LIKE'},
                        {field: 'invshlatest.shelves_name', title: __('LShelves_name'), operate: 'LIKE'},
                        {field: 'mbatch', title: __('Mbatch'),searchList: {"0":__('Mbatch 0'),"1":__('Mbatch 1')},formatter: Table.api.formatter.normal},
                        {field: 'fIsShelfLife', title: __('fIsShelfLife'),searchList: {"0":__('fIsShelfLife 0'),"1":__('fIsShelfLife 1')},formatter: Table.api.formatter.normal},
                        {field: 'fShelfLife', title: __('fShelfLife'),operate:false},
                        {field: 'safe_num', title: __('Safe_num'),operate:false},
                        {field: 'max_num', title: __('Max_num'),operate:false},
                        {field: 'min_num', title: __('Min_num'),operate:false},
                        //{field: 'source', title: __('Source'), searchList: {"1":__('Source 1')," 2":__('Source  2')}, formatter: Table.api.formatter.normal},
                        //{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                      //  {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            

            //打印
            $('#print-btn').click(function(){
                let allids =  Controller.api.selectedids(table);
                if(allids.length==0) return Toastr.error("请先选择物料");   
                Fast.api.open('information/inventory/print?inventory_id='+allids,'打印物料信息');
            })

            //
            $('.btn-danger').on('click',function(){
                Toastr.info("数据同步中请稍后....");
                var loadindex = layer.load(0); //0代表加载的风格，支持0-2
                $.post('information/inventory/getData',function(e){
                       if(e.code==1){
                         Toastr.success(e.msg);
                         parent.$("a.btn-refresh").trigger("click");
                       }else{
                         Toastr.error(e.msg);
                       }
                       layer.close(loadindex);
                    })
             })
             
             //复制并新增
             $('.btn-embossed-copy').click(function(){
            	 let allids =  Controller.api.selectedids(table);
                 if(allids.length==0) return Toastr.error("请先选择物料");  
                 if(allids.length>1) return Toastr.error("请先选择单个物料进行复制"); 
                 
                 let rows = table.bootstrapTable('getSelections');
                 var loadindex = layer.load(0); //0代表加载的风格，支持0-2
            	$.ajax({
                    url: "information/inventory/copy",
                    type: 'post',
                    dataType: 'json',
                    data: {number: rows[0].number},
                    success: function (ret) {
                    	layer.close(loadindex)
                        if(ret.code){
                        	Toastr.success('复制成功');
                        	$("a.btn-refresh").trigger("click");
                        }else{
                        	Toastr.error(ret.msg);
                        }
                    }, error: function (e) {
                    	Toastr.error(e.message);
                    }
                })
            })
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'information/inventory/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'information/inventory/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'information/inventory/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            $('#choose-shelves').click(function(){
               let house_id = $("#c-warehouse_id").val();
               top.Fast.api.open('information/shelves/choose?warehouse_id='+house_id,'选择货架或库区',{offset: 'r',callback:function(value){
                    console.log(value);
                    $("#c-shelves_id,#c-shelves_name").val(value.id);
                    $("#shelves_name").val(value.name);
                    $("#c-shelves_name").selectPageRefresh();
               }});
            })
            
            $(document).on("change", "#c-warehouse_id", function(){
            	$("#warehouse_name").val($('#c-warehouse_id').selectPageText());
			});
            
            $('.faupload-preview').bind('DOMNodeInserted',function (e){
                 $('.faupload-preview li').attr('class','col-xs-12');
            })
            
            Controller.api.bindevent();
        },
        choose:function(){
            
            $('#choose_id').click(function(){
              if(Fast.api.query("flag")=='tp'){//托盘
                let allids =  Controller.api.selectedids(chooseTable);
                Fast.api.close(allids);
              }else{
                let list =  chooseTable.bootstrapTable('getSelections');
                Fast.api.close(list);
              }
            })
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var chooseTable = $('#chooseTable')

            chooseTable.bootstrapTable({
                url: "information/inventory/choose" + location.search,
                pk: 'id',
                search:true,
                showToggle:false,
                singleSelect:Fast.api.query("flag")=='tp'?true:false,
                sortName: 'id',
                maintainSelected:true,//翻页记忆
                columns: [
                    [
                        {checkbox: true},
                        {field: 'number', title: __('Number'), operate: 'LIKE'},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'specification', title: __('Specification'), operate: 'LIKE'},
                        {field: 'attributes', title: __('Attributes'), operate: 'LIKE'},
                        {field: 'classification_name', title: __('Classification_name'), operate: 'LIKE'},
                       // {field: 'classification_id', title: __('Classification_id')},
                       // {field: 'switch', title: __('Switch'), searchList: {"0":__('Switch 0')," 1":__('Switch 1')},table: table, formatter: Table.api.formatter.toggle},
                        //{field: 'group', title: __('Group'), operate: 'LIKE'},
                        {field: 'unit', title: __('Unit'), operate: 'LIKE'},
                        {field: 'store_unit', title: __('StoreUnit'), operate: 'LIKE'},
                        {field: 'mbatch', title: __('Mbatch'),searchList: {'0':__('Mbatch 0'),'1':__('Mbatch 1')},formatter: Table.api.formatter.normal},
                        {field: 'source', title: __('Source'), searchList: {"1":__('Source 1')," 2":__('Source  2')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                       // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                       // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(chooseTable);

        },
        choosebyclass:function (){
            $('#choose_id').click(function(){
                let list =  chooseTable.bootstrapTable('getSelections');
                //let allids =  Controller.api.selectedids(chooseTable);
                // console.log(list);
                Fast.api.close(list);
            })

            $.ajax({
                url: "information/Inventoryclass/getTreeData2",
                type: 'post',
                dataType: 'json',
                data: {id: 2, pid: 1},
                success: function (ret) {
                    if (ret.hasOwnProperty("code")) {
                        var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                        if (ret.code === 1) {
                            //销毁已有的节点树
                            $("#treeview").jstree("destroy");
                            Controller.api.rendertree(data);
                        } else {
                            Backend.api.toastr.error(ret.msg);
                        }
                    }
                }, error: function (e) {
                    Backend.api.toastr.error(e.message);
                }
            })
            Table.api.init({
                extend: {
                   index_url:'information/inventory/choosebyclass'
                }
            });

            var chooseTable = $('#chooseTableClass')

            chooseTable.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url + location.search,
                pk: 'id',
                pageSize:30,
                pageList:"[30,60,90,100]",
                
                search:true,
                showToggle:false,
                
                // singleSelect:true,
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'number', title: __('Number')},
                        {field: 'name', title: __('Name')},
                        {field: 'specification', title: __('Specification')},
                        {field: 'attributes', title: __('Attributes'),operate:false},
                        {field: 'classification_id', title: '分类id', visible:false,data:'readonly',operate:'like'},
                        // {field: 'switch', title: __('Switch'), searchList: {"0":__('Switch 0')," 1":__('Switch 1')},table: table, formatter: Table.api.formatter.toggle},
                        {field: 'group', title: __('Group'),operate:false},
                        {field: 'unit', title: __('Unit')},
                        {field: 'mbatch', title: __('Mbatch'),searchList: {0:__('Mbatch 0'),"1":__('Mbatch 1')},formatter: Table.api.formatter.normal},
                        {field: 'source', title: __('Source'), searchList: {"1":__('Source 1'),"2":__('Source  2')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(chooseTable);
        },
        api: {
             //获取选中的行
             selectedids: function (table, current) {
                var options = table.bootstrapTable('getOptions');
                //如果有设置翻页记忆模式
                if (!current && options.maintainSelected) {
                    return options.selectedIds;
                }
                return $.map(table.bootstrapTable('getSelections'), function (row) {
                    return row[options.pk];
                });
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            rendertree: function (content) {
                $("#treeview")
                    .on('redraw.jstree', function (e) {
                        $(".layer-footer").attr("domrefresh", Math.random());
                    }).on('changed.jstree', function (e, data) {
                          let classification_id = data.node.id;
                          $("[name='classification_id']").val(classification_id);
                          $("[type='submit']").trigger('click')

                   }).jstree({
                        "plugins": [ "themes",'types'],
                        "core": {
                            'check_callback': true,
                            "data": content
                        }
                    });
            }
        }
    };
    return Controller;
});

function showQrcode(num = ''){
    if(num!=''&&!isNaN(num)){
        let index = num - 1
        let text = $("#cBatch_"+num).val()
        if($("#qrNo_"+num).val()!=''){
            text+='-'+$("#qrNo_"+num).val()
        }
        var inv_number = $("#inv_id_"+num).html()
        var qrcode_txt = 'WL'+inv_number+'!'+text
        //$('.qrcode_img').eq(index).html('')//清空原来 120

        $('.qrcode_img').eq(index).empty();
            //var qrcode_txt =  $('.qrcode_txt').eq(index).val();
        $('.qrcode_img').eq(index).qrcode({
            text: qrcode_txt,
            width: 120,
            height: 120
        });
        var canvas = $('.qrcode_img canvas')
        var img = canvas[0].toDataURL("image/png")
        $('.qrcode_img').eq(index).html("<img src='" + img + "'>")
        //$('.qrcode_img').eq(index).qrcode({render:'table',width: 80,height: 80,text:utf16to8(qrcode_txt)});
    }else{
        $('.qrcod_data').each(function(index,value){

            let num = index+1            
            var qrcode_txt =  $('.qrcode_txt').eq(index).val();
            $('#qrcode_img_'+num).qrcode({
                text: qrcode_txt,
                width: 120,
                height: 120
            });
            
            var canvas = $('.qrcode_img canvas')
            var img = canvas[0].toDataURL("image/png")
            //$('.qrcode_img').empty();
            $('#qrcode_img_'+num).html("<img src='" + img + "'>")

            //$('.qrcode_img').eq(index).qrcode({render:'table',width: 90,height: 90,text:utf16to8(qrcode_txt)});
        })
    }
}
//中文转码
function utf16to8(str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
        } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
        } else {
            out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
        }
    }
    return out;
}